<?php

namespace app\common\model;

use think\Model;

class Activity extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'images_url',
        'create_time_text',
        'share_back_image_url',
        'share_image_url',
        'start_time_text',
        'musicfile_url',
    ];

    public function getImagesUrlAttr($value, $data)
    {
        $value = $data['images'] ?? '';
        if ($value) {
            $images = explode(',', $value);
            foreach ($images as &$v) {
                $v = cdnurl($v, true);
            }
            return $images;
        } else {
            return [];
        }
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $data['createtime'] ?? '';
        if (!$value) {
            return '';
        }
        return date('Y-m-d H:i:s', $value);
    }

    public function getShareBackImageUrlAttr($value, $data)
    {
        $value = $data['share_back_image'] ?? '';
        return $value ? cdnurl($value, true) : '';
    }

    public function getShareImageUrlAttr($value, $data)
    {
        $value = $data['share_image'] ?? '';
        if ($value) {
            return cdnurl($value, true);
        } else {
            return '';
        }
    }

    public function getStartTimeTextAttr($value, $data)
    {
        $value = $data['start_time'] ?? '';
        if (!$value) {
            return '';
        }
        return date('Y/m/d', $value);
    }

    public function getMoneyAttr($value, $data)
    {
        $value = $data['money'] ?? '';
        if (!$value) {
            return 0;
        }
        return floatval($data['money']);
    }

    public function getMusicfileUrlAttr($value, $data)
    {
        $value = $data['musicfile'] ?? '';
        if ($value) {
            return cdnurl($value, true);
        } else {
            return '';
        }
    }

    public function getInfo($id)
    {
        $info = $this->where('id', $id)->find();

        if (is_null($info)) {
            return '活动不存在';
        }

        if ($info['status'] != 1) {
            return '活动未开始';
        }

        if ($info['start_time'] > time()) {
            return '活动未开始';
        }

        if ($info['end_time'] < time()) {
            return '活动已结束';
        }

        return $info;
    }
}
